<?php

namespace Api\Model;
class UserOrderModel extends BaseModel {

    /**
     * 用户订单列表
     * @param type $userId
     * @return type
     */
    public function orderList($userId) {
        $orderStatus = I('orderStatus', -2);
        $num = I('num') ? I('num') : 8;
        $page = I('page') ? I('page') : 1;
        $page = ($page - 1) * $num;

        if ($orderStatus == 2) {
            $statusSql = ' AND orderStatus IN (2,3,4,5,6,-3) ';
        } else {
            $statusSql = ' AND orderStatus = ' . $orderStatus;
        }

        $order = M('orders')->where('orderFlag = 1 and orderSN != 0 ' . $statusSql . ' AND userId=' . $userId)->field('orderId,orderNo,totalMoney,postage,supPrice,supPostage,payType,buyway,(totalMoney+postage+supPrice+supPostage) as priceSum,orderStatus,expressId,expressNo,isSource')->order('orderId DESC')->limit($page, $num)->select();

        if (empty($order))
            return $order;
        $data = array();
        foreach ($order as $v) {
            $v['expressName'] = M('express')->where('expressId=' . $v['expressId'])->getField('expressName');
            if (empty($v['expressName'])) {
                $v['expressName'] = '';
            }
            $sql = "select o.orderId,o.orderSN,o.orderNo,og.goodsNumber,g.marketPrice,g.shopPrice,g.goodsId,g.goodsSize,g.goodsWeight,g.goodsName,g.goodsThumbs,g.isSource,og.isAppraises "
                    . " from __PREFIX__orders as o left join __PREFIX__order_goods as og on o.orderId = og.orderId "
                    . " left join __PREFIX__goods as g on og.goodsId = g.goodsId where o.orderId = " . $v['orderId'];
            $v['goods'] = $this->query($sql);
            $data[] = $v;
        }

        return $data;
    }

    /**
     * 取消订单
     * @return type
     */
    public function cancelOrder($userId) {
        $m = M('orders');
        $orderId = I('orderId', 0);
        $m->orderFlag = 0;
        $rs = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->save();

        return $rs;
    }

    /**
     * 待付款订单结算
     * @return type
     */
    public function toCheckPay($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $m = M('orders');
        $orderId = I('orderId', 0);

        $m = M('orders');
        $order = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->field('orderId,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime')->find();
        if (empty($order))
            return $rt;
        $sql = 'select u.userId,u.userName,u.userPhoto,s.shopStatus from __PREFIX__shops as s left join __PREFIX__users as u on s.userId = u.userId where s.shopId = ' . $order['shopId'];
        $order['shopInfo'] = $this->queryRow($sql);
        $getOrderGoods = $this->getOrderGoods($orderId);
        $order['priceSum'] = $getOrderGoods['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];
        $order['payTypeName'] = M('payments')->where('id=' . $order['payType'])->getField('payName');
        $order['buywayName'] = M('buyway')->where('id=' . $order['buyway'])->getField('buyName');

        $order['goods'] = $getOrderGoods['goods'];
        $order['buywayList'] = M('buyway')->field('id,buyCode,buyName,buyConfig')->select();
        $order['payments'] = M('payments')->field('id,payCode,payName')->select();

        if ($order['buyway'] == 2) {
            $order['linestore'] = M('linestore')->where('storeId=' . $order['storeId'])->field('storeId,storeName,storeAddress,province,city,district,storeTel')->find();
            if (empty($order['linestore']))
                $order['linestore'] = array();
        }

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $order;
        return $rt;
    }

    /**
     * 提醒发货
     * @param type $userId
     * @return boolean
     */
    public function remind($userId) {
        $orderId = I('orderId', 0);
        if ($orderId == 0)
            return FALSE;
        $is_remind = M('order_reminds')->where('orderId = ' . $orderId . ' AND userId = ' . $userId . ' AND createTime = "' . date('Y-m-d') . '"')->count();
        if($is_remind > 0)
            return 10;
        $orderNo = M('orders')->where('orderId = ' . $orderId)->getField('orderNo');
        $orderInfo = M('orders')->where('orderNo = ' . $orderNo . ' AND isSource = 1')->find();
        $shopInfo = M('shops')->where('shopId = ' . $orderInfo['shopId'])->find();
//        $order_goods = M('order_goods')->where('orderNo = ' . $orderNo . ' AND isSource = 1')->find();
//        $goodsId = M('goods')->where('goodsId = ' . $order_goods['goodsId'])->find();
        $rs = D('Api/Sms')->sendSMScode($shopInfo['shopTel'], array('[' . $orderNo . ']'), 'remindTempId', 'remindTempId');
        $push = D('Api/Push');
        $rs = $push->PushToken('发货提醒：你的订单{' . $orderNo . '}请尽快发货！', $shopInfo['userId']);

        if ($rs['status'] == 1) {
            $data = array();
            $data['orderId'] = $orderId;
            $data['userId'] = $userId;
            $data['shopId'] = $orderInfo['shopId'];
            $data['createTime'] = date('Y-m-d');

            M('order_reminds')->add($data);
        }

        return TRUE;
    }

    /**
     * 订单详情
     * @return type
     */
    public function orderInfo($userId) {
        $m = M('orders');
        $orderId = I('orderId', 0);

        $order = $m->where('orderId=' . $orderId)->field('orderId,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,expressId,expressNo,createTime,isSource,userId')->find();
        if (empty($order))
            return $order;
        if ($userId != $order['userId'] && ($order['isSource'] == 0 || $order['buyway'] == 3)) {
            $order['userName'] = M('sys_configs')->where('fieldCode = "yuduUserName"')->getField('fieldValue');
            $order['userAddress'] = M('sys_configs')->where('fieldCode = "yuduAddress"')->getField('fieldValue');
            $order['userPhone'] = M('sys_configs')->where('fieldCode = "yuduPhone"')->getField('fieldValue');
        }
        $sql = 'select u.userId,u.userName,u.userPhoto,s.shopStatus from __PREFIX__shops as s left join __PREFIX__users as u on s.userId = u.userId where s.shopId = ' . $order['shopId'];
        $order['shopInfo'] = $this->queryRow($sql);
        $order['priceSum'] = $order['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];
        $order['payTypeName'] = M('payments')->where('id=' . $order['payType'])->getField('payName');
        $order['buywayName'] = M('buyway')->where('id=' . $order['buyway'])->getField('buyName');
        $order['goods'] = M('order_goods')->where('orderId = ' . $orderId)->select();
        $order['expressName'] = M('express')->where('expressId=' . $order['expressId'])->getField('expressName');
        if (empty($order['expressName']))
            $order['expressName'] = '';

        if ($order['buyway'] == 2) {
            $order['linestore'] = M('linestore')->where('storeId=' . $order['storeId'])->field('storeId,storeName,storeAddress,province,city,district,storeTel')->find();
            if (empty($order['linestore']))
                $order['linestore'] = array();
        }

        return $order;
    }

    /**
     * 确认收货
     * @param type $userId
     * @return boolean
     */
    public function confirm($userId) {
        $orderId = I('orderId', 0);
        $m = M('orders');
        $orderInfo = $m->where('orderId = ' . $orderId)->find();
        $rs = $m->where(' orderNo = ' . $orderInfo['orderNo'] . ' AND userId = ' . $userId)->save(array('orderStatus' => 2, 'upTime' => date('Y-m-d H:i:S')));

        $userInfo = M('shops')->where('shopId = ' . $orderInfo['shopId'])->find();
        if ($orderInfo['isSource'] == 1) {
            D('Api/Sms')->sendSMScode($userInfo['shopTel'], array($orderInfo['orderNo']), 'odfinishTempId', 'odfinishTempId');
            D('Api/Push')->PushToken('您的订单{'.$orderInfo['orderNo'].'}已结算成功，金额已自动发放到您的玉都钱包。', $userInfo['userId']);
        } else {
            D('Api/Sms')->sendSMScode($userInfo['shopTel'], array($orderInfo['orderNo']), 'reodfinishTempId', 'reodfinishTempId');
            D('Api/Push')->PushToken('您好，您转售的商品{'.$orderInfo['orderNo'].'}已交易成功，利润已自动发放到您的玉都钱包。', $userInfo['userId']);
        }

        return $rs;
    }

    /**
     * 快递信息
     * @param type $userId
     * @return boolean
     */
    public function expressNo($userId) {
        $orderId = I('orderId', 0);
        $data = array('expressName' => '圆通速递', 'expressNo' => '700074134800');

        return $data;
    }

    /**
     * 商品评价
     * @param type $userId
     * @return boolean
     */
    public function appraises($userId) {
        $orderId = I('orderId', 0);
        $goodsId = I('goodsId', 0);

        $shopId = M('orders')->where('orderId=' . $orderId)->getField('shopId');
        $rs = M('order_goods')->where('orderId=' . $orderId . ' and goodsId = ' . $goodsId)->getField('isAppraises');
        if ($rs != FALSE)
            return $rs;

        $data = array();
        $data['orderId'] = $orderId;
        $data['shopId'] = $shopId;
        $data['goodsId'] = $goodsId;
        $data['userId'] = $userId;
        $data['goodsScore'] = I('goodsScore');
        $data['serviceScore'] = I('goodsScore');
        $data['timeScore'] = I('goodsScore');
        $data['content'] = I('content');
        $data['createTime'] = date('Y-m-d H:i:s');

        $rs = M('goods_appraises')->add($data);
        M('order_goods')->where('orderId=' . $orderId . ' and goodsId = ' . $goodsId)->save(array('isAppraises' => 1));

        return $rs;
    }

    /**
     * 售后信息
     * @param type $userId
     * @return boolean
     */
    public function serviceInfo($userId) {
        $orderId = I('orderId', 0);
        $m = M('orders');
        $data = array('expressName' => '圆通速递', 'expressNo' => '700074134800');
        $order = $m->where('orderStatus in (2,3,4,5) and orderId=' . $orderId . ' and userId = ' . $userId)->field('orderId,orderNo,orderStatus,shopId')->find();
        if (empty($order))
            return $order;
        $order['goods'] = M('order_goods')->where('orderId=' . $orderId)->select();

        return $order;
    }

    /**
     * 提交退货
     * @param type $userId
     * @return boolean
     */
    public function returnGoods($userId) {
        $goodsId = I('goodsId', 0);
        $orderId = I('orderId', 0);

        if ($goodsId == 0 || $orderId == 0)
            return FALSE;

        $order = M('orders')->where('orderStatus = 2 and orderId=' . $orderId . ' and userId = ' . $userId)->field('orderId,orderNo,orderStatus,shopId')->find();
        if (empty($order))
            return $order;
        $goodsId = explode(',', $goodsId);
        $content = I('content');
        $pics = I('pics');

        $data = array();
        $data['orderId'] = $orderId;
        $data['userId'] = $userId;
        $data['shopId'] = $order['shopId'];
        $data['content'] = $content;
        $data['pics'] = $pics;

        $m = M('order_refund');
        foreach ($goodsId as $v) {
            $data['goodsId'] = $v;
            $rs = $m->add($data);
            if ($rs === FALSE)
                return FALSE;
        }
        $rs = M('orders')->where('orderStatus = 2 and orderId=' . $orderId . ' and userId = ' . $userId)->save(array('orderStatus' => 3, 'upTime' => date('Y-m-d H:i:S')));

        return TRUE;
    }

    /**
     * 自动更新用户订单状态
     * @param type $userId
     */
    public function upAutoOrderStatus($userId) {
        $m = M('orders');
        $date = date("Y-m-d", strtotime("-1 day"));
        $m->where('orderStatus = -2 and orderFlag = 1 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->save(array('orderFlag' => 0));

        //自动确认收货
        $date = date("Y-m-d", strtotime("-10 day"));
        $noComOrder = $m->where('orderStatus = 1 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->field('orderId, orderNo, orderSN, date_format(`createTime`, "%Y-%m-%d") AS time ')->select();
        $noComOrderId = '';
        foreach ($noComOrder as $v) {
            $noComOrderId .= $v['orderId'] . ',';
        }
        $noComOrderId = trim($noComOrderId, ',');
        if (!empty($noComOrderId)) {
            $rs = $this->upOrderStatus($noComOrderId, 2);
        }

        //3天后自动完成订单
        $this->_upOrderToFinish($userId);

        //2天未发货订单自动取消
        $this->upNoshiftOrder($userId);

        //15天完成的订单金额转到余额
        $this->upFinishProfitOrder($userId);
    }


    /**
     * 用户订单数量统计
     */
    public function userOrderSum($userId) {
        $m = M('orders');
        $sum = array();
        $sum['nopay'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = -2 and userId = ' . $userId)->count();
        $sum['noshipping'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = 0 and userId = ' . $userId)->count();
        $sum['server'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus in(2,3,4,5,6,-3) and userId = ' . $userId)->count();
        $sum['nosign'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = 1 and userId = ' . $userId)->count();

        return $sum;
    }

    /**
     * 销售订单数量统计
     */
    public function shopOrderSum($userId) {
        $m = M('orders');
        $shopId = M('shops')->where('userId=' . $userId)->getField('shopId');
        $sum = array();
        $sum['nopay'] = $m->where('orderFlag = 1 and orderStatus = -2 and shopId = ' . $shopId)->count();
        $sum['noshipping'] = $m->where('orderFlag = 1 and orderStatus = 0 and shopId = ' . $shopId)->count();
        $sum['server'] = $m->where('orderFlag = 1 and orderStatus in(2,3,4,5) and shopId = ' . $shopId)->count();
        $sum['nosign'] = $m->where('orderFlag = 1 and orderStatus = 1 and shopId = ' . $shopId)->count();

        return $sum;
    }

}